package com.hongyun.tms.infra.excel.converter.enums;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.hongyun.tms.exception.DictNotFoundException;

import java.util.Objects;

/**
 * 通用的枚举翻译类，用于 Excel 导入导出。
 *
 * @param <T> 枚举类型
 * @param <K> 枚举 code 类型 (如 String 或 Integer)
 * @author peng.li
 * @date 2024-09-14
 */
public abstract class AbstractEnumConverter<T extends Enum<T>, K> implements Converter<K> {

    /**
     * 将 Java 数据转换为 Excel 数据 (导出)
     */
    @Override
    public WriteCellData<?> convertToExcelData(K value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        String stringValue = null;
        try {
            stringValue = getEnumDescByCode(value);
        } catch (Exception e) {
            stringValue = getEnumDescByCode((K) value.toString());
        }
//        String stringValue = getEnumDescByCode((K) value.toString());
        return new WriteCellData<>(stringValue);
    }

    /**
     * 将 Excel 数据转换为 Java 数据 (导入)
     */
    @Override
    public K convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) {
        String text = cellData.getStringValue();
        K code = getCodeByDesc(text);

        if (Objects.isNull(code)) {
            throw new DictNotFoundException("未知字典项: " + text + "，请根据模板填写规范的值");
        }

        return code;
    }

    /**
     * 根据 code 获取对应的枚举描述
     */
    protected abstract String getEnumDescByCode(K code);

    /**
     * 根据描述获取对应的枚举 code
     */
    protected abstract K getCodeByDesc(String desc);
}
